let expess = require('express');
let router = expess.Router();
let mgdb = require('../../utils/mgdb')
let bcrypt = require('../../utils/bcrypt')
let jwt = require('../../utils/jwt')

router.post('/',(req,res,next)=>{
  
  //获取username,password
  let {username,password} = req.body

  //设定必传参数
  if(!username || !password){
    res.send({
      err:1,
      msg:'用户名密码为必传参数'
    })

    return;
  }

  //兜库，查询用户密码(解密)
  mgdb.open({
    collectionName:'user'
  }).then(
   ({collection,client}) => {
    collection.find({
      username
    }).toArray((err,result)=>{
      if(err){
        res.send({err:1,msg:'集合操作失败'})
        client.close()
      }else{
        if(result.length>0){
          //校验密码
          let bl = bcrypt.compareSync(password,result[0].password);
          if(bl){
            //成功  生成token 发给客户端
            let token  = jwt.sign({username,_id:result[0]._id})
            delete result[0].username;
            delete result[0].password;

            res.send({err:0,msg:'登录成功',data:result[0],token})

          }else{
            res.send({err:1,msg:'用户名或者密码有误'})
            client.close()
          }
        }else{
          res.send({err:1,msg:'用户名或者密码有误'})
          client.close()
        }
      }
    })
   } 
  ).catch(
    ({err,client}) => {
      res.send({err:1,msg:'集合操作失败'})
      client.close()
    }
  )

})

module.exports = router;